import Vue from 'vue'
import { getAllUnread } from '@/api/message'
import { getToken } from '@/utils/user'
// setInterval(() => {
//   Vue.prototype.$storeAction('getUnreadCount')
// }, 5000)

export default {
  state: () => {
    return {
      list: [{
        pagePath: '/pages/Home/index',
        scheme: 'home',
        iconPath: '/static/imgs/tabbar/home.png',
        selectedIconPath: '/static/imgs/tabbar/home-active.png',
        text: '首页',
      },
      /** {
        pagePath: '/pages/Case/index',
        scheme: 'case',
        iconPath: '/static/imgs/tabbar/case.png',
        selectedIconPath: '/static/imgs/tabbar/case-active.png',
        text: '案例',
      },*/
      {
        iconPath: '/static/imgs/add.jpg',
        midButton: true,
      },
      /** {
        pagePath: '/pages/Team/index',
        scheme: 'case',
        iconPath: '/static/imgs/tabbar/team.png',
        selectedIconPath: '/static/imgs/tabbar/team-active.png',
        text: '组队',
      },*/
      // TODO: 组队和案例的图片需要添加。
      {
        pagePath: '/pages/User/index',
        scheme: 'myPage',
        iconPath: '/static/imgs/tabbar/me.png',
        selectedIconPath: '/static/imgs/tabbar/me-active.png',
        text: '我的',
      }]
    }
  },
  mutations: {
    setMessageCount(state, count) {
      /* 如果这次的count和上次不一样，说明列表要刷新，通知messages列表刷新 */
      if (state.list[ 3 ].count !== count) {
        uni.$emit('refreshMessages')
      }
      state.list[ 3 ].count = count
    }
  },
  actions: {
    async getUnreadCount({ state, commit }) {
      const pages = getCurrentPages()

      /* 无token不执行 */
      if (!getToken()) {
        return
      }
      /* 不在首页不执行 */
      if (pages.length > 1) {
        return
      }
      /* 只有一个页面栈，但不是首页，不执行 */
      if (!state.list.find(item => item.pagePath === pages[ 0 ].$page.fullPath)) {
        return
      }
      const res = await getAllUnread()

      commit('setMessageCount', res.systemMessageCount)
    }
  }
}
